<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/12/26
  Time: 19:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/layui/css/layui.css">
</head>
<body>
<form class="layui-form layui-form-pane">
    <div class="layui-form-item">
    <label class="layui-form-label">头像</label>
    <div class="layui-inline">
        <img id="userImg" style="width: 200px;border: #c0c4cc 1px solid" onerror="javascript:this.src='${pageContext.request.contextPath}/imgs/default.jpg'" src="${pageContext.request.contextPath}/${user.img}" alt="">
    </div>
    </div>
    <div class="layui-form-item" style="margin-top: 30px">
        <button style="margin-left: 110px;width:200px;" class="layui-btn" type="button" id="uploadBtn">修改头像</button>
    </div>
</form>
<script src="${pageContext.request.contextPath}/resources/layui/layui.js"></script>
<script>
    layui.use(['form','layer','jquery','upload'],function () {
        let form = layui.form;
        let layer = layui.layer;
        let $ = layui.jquery;
        let upload = layui.upload;
        let cxt = "${pageContext.request.contextPath}";
        let uploadOpt = {
            elem:"#userImg",//文件上传的容器 触发文件上传操作
            url:cxt+"/user.do?service=upload",//接收文件上传数据的接口
            accept:"file",//允许上传的文件类型  默认images
            acceptMime:"image/*",//文件筛选框 允许的类型
            exts:"jpg|png",//文件的后缀
            auto:false,//是否选择完文件后就进行网络请求
            bindAction:"#uploadBtn",//手动触发上传的按钮
            field:"img",//隐藏的那个文件域的name属性的值  也是网络请求的name的属性值
            size:1024,//允许文件上传的大小 单位KB
            choose:function (obj) {//选择了文件后调用的方法
                console.log("选择了文件的回调");
                console.log(obj);
                //图片的预览
                obj.preview(function (index, file, result) {
                    console.log(index);
                    console.log(file);
                    console.log(result);
                    //为图片设置Base64编码字符串
                    $("#userImg").attr("src",result);
                });
            },
            done:function (rs,index,upload) {
                //rs 就是服务器返回的数据
                //index 文件索引
                //upload 文件上传对象 可以上传失败 重新上传
                console.log(rs);
                if (rs.code == 200){
                    //上传成功了
                    //修改 登录的头像值  登录的头像是一个URL
                    //获取到上传的图片的URL
                    let imgUrl = rs.data;
                    //由于是修改的父窗口中的头像 所以需要使用 window.parent
                    window.parent.document.getElementById("loginImg").src = imgUrl;
                }
            }

        };
        upload.render(uploadOpt);

    })
</script>
</body>
</html>
